import * as React from "react";

export const useDebounce = &lt;T&gt;(value: T, delay = 500) =&gt; {
  const [debouncedValue, setDebouncedValue] = React.useState(value);

  React.useEffect(() =&gt; {
    const handler: NodeJS.Timeout = setTimeout(() =&gt; {
      setDebouncedValue(value);
    }, delay);

    // Cancel the timeout if value changes (also on delay change or unmount)
    return () =&gt; {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};
